// book
let mongoose = require('mongoose');
let lodash = require('lodash');
let pinyinUtils = require('../utils/pinyinUtils');

let schema = module.exports = new mongoose.Schema({
    bookNum: {
        type: String
    },
    id: String,
    isbn10: String,
    isbn13: String,
    title: String,
    titlePinyin: {
        full: [String], // 全名拼音 有空格分隔
        fullWithSymbol: [String], // 全名拼音,有音标
        prefixes: [String] // 声母部分
    },
    origin_title: String,
    alt_title: String,
    subtitle: String,
    url: String,
    alt: String,
    image: String,
    images: {
        small: String,
        large: String,
        medium: String
    },
    author: [String],
    translator: [String],
    publisher: String,
    pubdate: String,
    rating: {
        max: Number,
        numRaters: Number,
        average: Number,
        min: Number
    },
    tags: [{
        count: Number, name: String
    }],
    binding: String,
    // price: Number,
    price: String,
    series: {
        id: String,
        title: String
    },
    // pages: Number,
    pages: String,
    author_intro: String,
    summary: String,
    catalog: String,
    ebook_url: String,
    ebook_price: Number,
    awsUrl: String, // 亚马逊书籍详情页链接
    isDelete: {
        type: Boolean,
        default: false
    }, // 是否删除

    createTime: {type: Date, default: Date.now}, // 创建时间
    updateTime: {type: Date, default: Date.now}, // 更新时间
    deleteTime: Date // 删除时间
});

// index
// title
schema.index({'title': 'text'});
// title pinyin
schema.index({'titlePinyin.fullName.0': 1});
// isbn10
schema.index({'isbn10': 1});
// isbn13
schema.index({'isbn13': 1});

//name path
schema.path('title').set(function (newVal) {
    let originalVal = this.title;
    if (originalVal !== newVal) {
        this.isTitleChanged = true;
    }
    return newVal;
});


schema.pre('save', function (next) {
    this.title = lodash.trim(this.title);
    if (this.isTitleChanged) {
        this.titlePinyin = pinyinUtils.getModelFormat(this.title);
    }
    next();
});

